package controllers;

import negocio.ObjetivoEstrategico;
import controllers.util.JsfUtil;
import controllers.util.JsfUtil.PersistAction;
import beans.ObjetivoEstrategicoFacade;
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.context.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import negocio.Valor;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.mindmap.DefaultMindmapNode;
import org.primefaces.model.mindmap.MindmapNode;

@Named("objetivoEstrategicoController")
@RequestScoped
public class ObjetivoEstrategicoController implements Serializable {

    @EJB
    private beans.ObjetivoEstrategicoFacade ejbFacade;
    private List<ObjetivoEstrategico> items = null;
    private ObjetivoEstrategico selected;
    private List<ObjetivoEstrategico> filteredItems;

    public ObjetivoEstrategicoController() {
    }
    

    public void init() {
        items=this.getItems();
    }

    public ObjetivoEstrategico getSelected() {
        return selected;
    }

    public void setSelected(ObjetivoEstrategico selected) {
        this.selected = selected;
    }
    
    public void setFilteredItems(List<ObjetivoEstrategico> filteredItems){
        this.filteredItems=filteredItems;
        System.out.println("==============="+this.filteredItems.size());
    }

    protected void setEmbeddableKeys() {
    }

    protected void initializeEmbeddableKey() {
    }

    private ObjetivoEstrategicoFacade getFacade() {
        return ejbFacade;
    }

    public ObjetivoEstrategico prepareCreate() {
        selected = new ObjetivoEstrategico();
        initializeEmbeddableKey();
        return selected;
    }

    public void create() {
        persist(PersistAction.CREATE, ResourceBundle.getBundle("/Bundle").getString("ObjetivoEstrategicoCreated"));
        if (!JsfUtil.isValidationFailed()) {
            items = null;    // Invalidate list of items to trigger re-query.
        }
    }

    public void update() {
        persist(PersistAction.UPDATE, ResourceBundle.getBundle("/Bundle").getString("ObjetivoEstrategicoUpdated"));
    }

    public void destroy() {
        persist(PersistAction.DELETE, ResourceBundle.getBundle("/Bundle").getString("ObjetivoEstrategicoDeleted"));
        if (!JsfUtil.isValidationFailed()) {
            selected = null; // Remove selection
            items = null;    // Invalidate list of items to trigger re-query.
        }
    }

    public List<ObjetivoEstrategico> getItems() {
        if (items == null) {
            items = getFacade().findAll();
        }
        return items;
    }

    private void persist(PersistAction persistAction, String successMessage) {
        if (selected != null) {
            setEmbeddableKeys();
            try {
                if (persistAction != PersistAction.DELETE) {
                    getFacade().edit(selected);
                } else {
                    getFacade().remove(selected);
                }
                JsfUtil.addSuccessMessage(successMessage);
            } catch (EJBException ex) {
                String msg = "";
                Throwable cause = ex.getCause();
                if (cause != null) {
                    msg = cause.getLocalizedMessage();
                }
                if (msg.length() > 0) {
                    JsfUtil.addErrorMessage(msg);
                } else {
                    JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
                }
            } catch (Exception ex) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
                JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            }
        }
    }

    public ObjetivoEstrategico getObjetivoEstrategico(java.lang.Integer id) {
        return getFacade().find(id);
    }

    public List<ObjetivoEstrategico> getItemsAvailableSelectMany() {
        return getFacade().findAll();
    }
    
    public List<ObjetivoEstrategico> getItemsAvailableSelectOne() {
        return getFacade().findAll();
    }

    @FacesConverter(forClass = ObjetivoEstrategico.class)
    public static class ObjetivoEstrategicoControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ObjetivoEstrategicoController controller = (ObjetivoEstrategicoController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "objetivoEstrategicoController");
            return controller.getObjetivoEstrategico(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        @Override
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof ObjetivoEstrategico) {
                ObjetivoEstrategico o = (ObjetivoEstrategico) object;
                return getStringKey(o.getIdobjetivoEstrategico());
            } else {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), ObjetivoEstrategico.class.getName()});
                return null;
            }
        }
        
        

    }
    
    /*public String getCurrentValor(int id){
        Valor v=null;
        Iterator<Valor> it=this.getObjetivoEstrategico(id).getIndicadorIdindicador().getValorCollection().iterator();
        while(it.hasNext()){
            v=it.next();
        }
        return v.getValor().toString();
    }*/

    public List<ObjetivoEstrategico> getFilteredItems(){
        return this.filteredItems;
    }
   
    private MindmapNode root;
     
    private MindmapNode selectedNode;
    
    private MindmapNode nodef;
    private MindmapNode nodec;
    private MindmapNode nodep;
    private MindmapNode nodea;
     
    public void createMindmapView() {
        
        //ObjetivoEstrategicoController oec=new ObjetivoEstrategicoController();
        List<ObjetivoEstrategico> objetivos=this.getItems();
        
        
        root = new DefaultMindmapNode("Mapa Estrategico Organizacional - TESECOMP", "", "2E9AFE", false);
         
        MindmapNode node=null;
        
        MindmapNode nodef=null;
        nodef=new DefaultMindmapNode("Perpectiva Financiera", "", "A9D0F5", true);
        //root.addNode(nodef);
        MindmapNode nodec=null;
        nodec=new DefaultMindmapNode("Perpectiva Clientes", "", "A9D0F5", true);
        //root.addNode(nodec);
        MindmapNode nodep=null;
        nodep=new DefaultMindmapNode("Perpectiva Procesos", "", "A9D0F5", true);
        //root.addNode(node);
        MindmapNode nodea=null;
        nodea=new DefaultMindmapNode("Perpectiva Aprendizaje y Crecimiento", "", "A9D0F5", true);
        //root.addNode(node);
        
        for(int i=0;i<objetivos.size();i++){
            node=new DefaultMindmapNode(objetivos.get(i).getDefinicion(),"",this.getCodigoColor(objetivos.get(i).getCurrentSemaforo()),false);
            if(objetivos.get(i).getCurrentPerspectiva().equals("Financiera")){
                nodef.addNode(node);
            }
            else if(objetivos.get(i).getCurrentPerspectiva().equals("Clientes")){
                nodec.addNode(node);
            }
            else if(objetivos.get(i).getCurrentPerspectiva().equals("Procesos")){
                nodep.addNode(node);
            }
            else {
                nodea.addNode(node);
            }
        }
        
        /*this.nodef=nodef;
        this.nodec=nodec;
        this.nodep=nodep;
        this.nodea=nodea;*/
        
        root.addNode(nodef);
        root.addNode(nodec);
        root.addNode(nodep);
        root.addNode(nodea);
    }
 
    public MindmapNode getRoot() {
        this.createMindmapView();
        return root;
    }
    
    public MindmapNode getNodef() {
        this.createMindmapView();
        return nodef;
    }
    
     public MindmapNode getNodec() {
        this.createMindmapView();
        return nodec;
    }
     
      public MindmapNode getNodep() {
        this.createMindmapView();
        return nodep;
    }
      
       public MindmapNode getNodea() {
        this.createMindmapView();
        return nodea;
    }
 
    public MindmapNode getSelectedNode() {
        return selectedNode;
    }
    public void setSelectedNode(MindmapNode selectedNode) {
        this.selectedNode = selectedNode;
    }
 
    public void onNodeSelect(SelectEvent event) {
        MindmapNode node = (MindmapNode) event.getObject();
         
    }
     
    public void onNodeDblselect(SelectEvent event) {
        this.selectedNode = (MindmapNode) event.getObject();       
    }
    
    public String getCodigoColor(String color){
        if(color.equals("Amarillo")){
            return "FACC2E";
        }
        else if(color.equals("Rojo")){
            return "FF0000";
        }
        else 
            return "3ADF00";
    }
    
   
    
}
